<template>
  <div
    class="login"
    v-loading="bgpload"
    element-loading-text="加载中..."
    element-loading-background="rgba(255, 255, 255, 1)"
  >
    <div class="left-wrap">
      <div class="logo">
        <img src="/static/images/web.png" />
      </div>
    </div>
    <div class="right-wrap">
      <div class="header">
        <h1>{{systemName}}</h1>
      </div>
      <div class="login-wrap">
        <div class="form">
          <h3>{{$t('login.title')}}</h3>
          <el-col>
            <span class="input-label">{{$t('login.label[0]')}}</span>
            <el-input placeholder="username" size="medium" v-model.trim="account" />
          </el-col>
          <el-col>
            <span class="input-label">{{$t('login.label[1]')}}</span>
            <el-input
              type="password"
              placeholder="password"
              size="medium"
              v-model.trim="password"
              autocomplete="off"
              @keyup.enter.native="login"
              maxlength="100"
            />
          </el-col>
          <el-col>
            <span class="input-label">{{$t('login.label[2]')}}</span>
            <el-col class="code">
              <el-input
                size="medium"
                placeholder="verification code"
                v-model.trim="code"
                @keyup.enter.native="login"
                @input="watchCode"
                maxlength="20"
              />
              <identify-code class="code-img" :changeCode.sync="identifyCode"></identify-code>
            </el-col>
          </el-col>
          <el-col>
            <el-button
              class="login-btn"
              @click="login"
              :loading="loading"
              :disabled="loginDis"
              :style="loginDis ? 'color: #bcbec2;background-color: #f4f4f5;border-color: #e9e9eb;' : ''"
            >{{$t('login.btn')}}</el-button>
            <span>©2021 安徽皖通邮电股份有限公司</span>
          </el-col>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 系统配置项
import setting from '@/config/setting';
// 验证码
import IdentifyCode from '@common/IdentifyCode';
// 二次加密
import crypto from '@/utils/crypto';
// 菜单目录
import { getMenuList } from '@/api/menuApi.js';

export default {
  components: { IdentifyCode },
  data () {
    return {
      // 系统语言
      language: '',
      // 当前生成的验证码
      identifyCode: '',
      // 系统名称
      systemName: setting.systemName,
      // 用户名
      account: setting.login.username,
      // 密码
      password: setting.login.password,
      // 验证码
      code: '',
      // 加载状态
      loading: false,
      // 按钮状态
      loginDis: true,
      // loading状态
      bgpload: true
    };
  },
  beforeDestroy () {
    let _this = this;
    _this.bgpload = false;
  },
  created () {
    if (window.location) {
      let _this = this;
      let code = window.location.hash;
      let neId = code.substring(code.indexOf('=') + 1, code.indexOf('&'));
      let type = code.substring(code.lastIndexOf('=') + 1, code.length);
      if (code.indexOf('bgp') > -1 || code.indexOf('application') > -1 || code.indexOf('deviceInfo') > -1) {
        this.$http.get({
          url: '/action/csrf'
        }).then(res => {
          let time = new Date().getTime();
          let data = {
            time: time,
            type: 'WEB',
            username: 'admin',
            password: crypto.hmac(time + crypto.hash('ZXWT_2017!uap'), res.token),
            locale: this.language === 'en' ? 'en_US' : 'zh_CN',
            'remember-me': 'off'
          };
          this.$http.post({
            url: `/action/login?${res.parameterName}=${res.token}`,
            data
          }).then(result => {
            this.loading = true;
            let token = res.token;
            this.$http.get({
              url: '/api/gateway/user/self'
            }).then(res => {
              let obj = {
                token,
                user: res
              };
              this.$store.dispatch('user/setUserInfo', obj);
              this.$store.dispatch('user/setLoginStatus', true);
              getMenuList();
              // eslint-disable-next-line max-nested-callbacks
              setTimeout(async () => {
                await this.$http.put({
                  url: '/api/sys/preferences',
                  data: {
                    'web.locale': this.language === 'en' ? 'en_US' : 'zh_CN',
                  }
                });
                if (code.indexOf('deviceInfo') > -1) {
                  this.$router.push({
                    path: '/monitor/device-info',
                    query: {
                      id: neId
                    }
                  });
                } else {
                  sessionStorage.setItem('jump', JSON.stringify({
                    neId,
                    type,
                    tag: code.indexOf('bgp') > -1 ? 'bgp' : 'application'
                  }));
                  if (type === 'CPE') {
                    this.$router.push('/configure/access');
                  } else {
                    this.$router.push('/configure/mixed');
                  }
                }
              }, 1000);
            });
          });
        });
      } else {
        _this.bgpload = false;
      }
    }
    this.initLanguage();
  },
  methods: {
    // 监听验证码
    watchCode () {
      let _this = this;
      if (_this.code.toUpperCase() !== _this.identifyCode.toUpperCase()) {
        _this.loginDis = true;
      } else {
        _this.loginDis = false;
      }
    },
    // 登录
    login () {
      let { account, password, code } = this;
      if (!account) {
        this.showTips(0); return;
      }
      if (!password) {
        this.showTips(1); return;
      }
      if (!code) {
        this.showTips(2); return;
      }
      if (code.toUpperCase() !== this.identifyCode.toUpperCase()) {
        this.showTips(3); return;
      }
      this.$http.get({
        url: '/action/csrf'
      }).then(res => {
        let time = new Date().getTime();
        let data = {
          time: time,
          type: 'WEB',
          username: account,
          password: crypto.hmac(time + crypto.hash(this.password), res.token),
          locale: this.language === 'en' ? 'en_US' : 'zh_CN',
          'remember-me': 'off'
        };
        this.$http.post({
          url: `/action/login?${res.parameterName}=${res.token}`,
          data
        }).then(result => {
          this.loading = true;
          let token = res.token;
          this.$http.get({
            url: '/api/gateway/user/self'
          }).then(res => {
            let obj = {
              token,
              user: res
            };
            this.$store.dispatch('user/setUserInfo', obj);
            this.$store.dispatch('user/setLoginStatus', true);
            getMenuList();
            // eslint-disable-next-line max-nested-callbacks
            setTimeout(async () => {
              await this.$http.put({
                url: '/api/sys/preferences',
                data: {
                  'web.locale': this.language === 'en' ? 'en_US' : 'zh_CN',
                }
              });
              this.$router.push('/');
            }, 1000);
          });
        });
      });
    },
    // 初始化语言
    initLanguage () {
      let sys = JSON.parse(localStorage.getItem('sys'));
      if (sys) {
        let { language } = sys.user;
        if (language) {
          this.language = language;
          this.$i18n.locale = language;
          this.$store.dispatch('user/setLanguage', language);
        }
      }
    },
    // 消息提示
    showTips (index) {
      this.$message.error(this.$t(`login.tips[${index}]`));
    }
  }
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100vh;
  box-sizing: border-box;
  display: flex;
  background: url("/static/images/bg.jpg") no-repeat 100% 100%;
  background-color: #1169ff;
  ::v-deep .el-input__inner {
    &:focus {
      border: 1px solid #4e83fd;
    }
  }

  ::v-deep .el-input--medium .el-input__inner {
    height: 40px;
    line-height: 40px;
  }

  .left-wrap {
    width: 800px;
    height: 100%;
    background: transparent;
    background-size: cover;
    padding: 20px;
    box-sizing: border-box;

    .logo {
      position: relative;
      img {
        display: block;
        width: 580px;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: 20vh auto;
      }
    }
  }

  .right-wrap {
    width: calc(100% - 800px);
    height: 100%;
    position: relative;

    .header {
      display: none;
    }

    .login-wrap {
      width: 440px;
      height: 450px;
      border-radius: 5px;
      overflow: hidden;
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
      background-size: cover;
      box-shadow: 0 0 10px rgba(28, 76, 186, 0.1);

      .form {
        widows: 100%;
        height: 100%;
        box-sizing: border-box;
        padding: 25px 30px;
        background: #fff;

        h3 {
          color: #555;
          font-size: 23px;
          text-align: center;
          font-weight: 500;
          margin: 15px 0;
        }

        .input-label {
          color: #333;
          font-size: 14px;
          padding: 8px 0;
          display: block;
        }

        .code {
          display: flex;
          justify-content: space-between;

          .el-input {
            flex: 1;
            margin-right: 20px;
          }
          .code-img {
            cursor: pointer;
          }
        }

        .login-btn {
          width: 100%;
          height: 40px;
          margin: 15px 0 20px 0;
          border: 0;
          color: #fff;
          background: #4e83fd;
        }
      }
    }
  }
}

@media only screen and (max-width: $device-ipad-pro) {
  .login {
    width: 100%;
    height: 100vh;

    .left-wrap {
      display: none;
    }

    .right-wrap {
      width: 100%;
      background: #fff;

      .header {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 20vh;

        h1 {
          font-weight: 500;
          margin-left: 15px;
        }
      }

      .login-wrap {
        width: 100%;
        height: auto;
        border-radius: 0;
        position: relative;
        box-shadow: none;

        .form {
          padding: 0px 30px;

          h3 {
            display: none;
          }
        }
      }
    }
  }
}
</style>
